﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System;
using ImoviesBlazorAntPro.Shared;
using System.Collections.Generic;

namespace ImoviesBlazorAntPro.Server.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class LoginController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly SignInManager<IdentityUser> _signInManager;

        private readonly UserManager<IdentityUser> _userManager;

        public LoginController(IConfiguration configuration, SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
        {
            _configuration = configuration;
            _signInManager = signInManager;
            _userManager = userManager;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginModel login)
        {
            var result = await _signInManager.PasswordSignInAsync(login.UserName, login.Password, false, false);
            if (!result.Succeeded)
            {
                return BadRequest(new LoginResult
                {
                    Successful = false,
                    Error = "用户名或密码不正确！"
                });
            }
            var roles = await _userManager.GetRolesAsync(new IdentityUser { UserName = login.UserName });
            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, login.UserName));
            if (roles.Contains("admin"))
            {
                claims.Add(new Claim(ClaimTypes.Role, "admin"));
            }
            else
            {
                claims.Add(new Claim(ClaimTypes.Role, "guest"));
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:JwtSecurityKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiry = DateTime.Now.AddHours(Convert.ToInt32(_configuration["Jwt:JwtExpiryInHour"]));

            try
            {
                // 生成token
                var token = new JwtSecurityToken(
                    _configuration["Jwt:JwtIssuer"],
                    _configuration["Jwt:JwtAudience"],
                    claims,
                    expires: expiry,
                    signingCredentials: creds
                );

                return Ok(new LoginResult
                {
                    Successful = true,
                    Token = new JwtSecurityTokenHandler().WriteToken(token),
                    //Role = roles.Contains("admin") ? "admin":"guest"
                });
            }
            catch (Exception e)
            {
                return Ok(new LoginResult
                {
                    Successful = false,
                    Error = e.Message
                });
            }

        }
    }
}
